package com.xncoding.easypoi.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.xhtmlrenderer.pdf.ITextRenderer;


import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;

public class PDFUtils {

	public static Logger log = Logger.getLogger(PDFUtils.class);

	//PDF页眉、页脚定制工具
	private PDFHeaderFooter PDFHeaderFooter;

	public String exportToFile(String saveFilePath,String templatePath,Object data,boolean isHeaderFooter){
		FileOutputStream outputStream=null;
		 PDFBuilder builder =null;
		try {
		if(StringUtils.isEmpty(templatePath)){
			log.error("模板路径为空");
			return "";
		}
		if(StringUtils.isEmpty(saveFilePath)){
			log.error("保存路径为空");
			return "";
		}

		File file=new File(saveFilePath);
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		
			//获取html内容
			String htmlData= getContent(templatePath, data);

			//设置输出路径
			outputStream=new FileOutputStream(saveFilePath);
			//设置文档大小
			Document document = new Document(PageSize.A4);
			PdfWriter writer = PdfWriter.getInstance(document, outputStream);
             if(isHeaderFooter){
            	 //设置页眉页脚
                  PDFHeaderFooter=new PDFHeaderFooter();
            	 builder= new PDFBuilder(PDFHeaderFooter,data,10);
             }else {
            	 builder  =	 new PDFBuilder(null,data,10);
			}
			writer.setPageEvent(builder);

			//输出为PDF文件
			convertToPDF(writer,document,htmlData);
		}catch(Exception ex){
			log.error("PDF生成失败:"+ ExceptionUtils.getFullStackTrace(ex));
		}finally{
			IOUtils.closeQuietly(outputStream);
		}
		return saveFilePath;
	}




	/**
	 * 生成PDF到输出流中（ServletOutputStream用于下载PDF）

	 * @param data 输入到FTL中的数据
	 * @param response HttpServletResponse
	 * @return
	 */
	public  OutputStream exportToResponse(String templatePath,Object data, HttpServletResponse response){

		String html= getContent(templatePath,data);
		OutputStream out = null;
		try{
			//ITextRenderer render = null;
			out = response.getOutputStream();
			//设置文档大小
			Document document = new Document(PageSize.A4);
			PdfWriter writer = PdfWriter.getInstance(document, out);
			//设置页眉页脚
			PDFBuilder builder = new PDFBuilder(PDFHeaderFooter,data);
			writer.setPageEvent(builder);
			//输出为PDF文件
			convertToPDF(writer,document,html);
		}catch (Exception ex){
			// throw  new PDFException("PDF export to response fail",ex);
		}
		return out;

	}

	/**
	 * @description PDF文件生成
	 */
	private  void convertToPDF(PdfWriter writer,Document document,String htmlString){
		document.open();
		//获取字体路径
		String fontPath=PDFUtils.class.getClassLoader().getResource("").getPath()+"fonts";
		try {
			XMLWorkerHelper.getInstance().parseXHtml(writer,document,
					new ByteArrayInputStream(htmlString.getBytes()),
					XMLWorkerHelper.class.getResourceAsStream("/default.css"),
					Charset.forName("UTF-8"),new XMLWorkerFontProvider(fontPath));
		} catch (IOException e) {
			log.error("PDF文件生成异常"+e.getMessage());
		}finally {
			document.close();
		}

	}




	/**
	 * @description 获取模板内容
	 */
	private  String getContent(String templatePath,Object data){
		String html ="";
		StringWriter writer = new StringWriter();
		try{
			String templateFileName=getTemplateName(templatePath).replace("\\", "/");
			String templateFilePath=getTemplatePath(templatePath).replace("\\", "/");
			if(templateFileName.lastIndexOf(".ftl")==-1){
				log.error("模板文件格式不对");
				return "";
			}
			Configuration config = new Configuration(Configuration.VERSION_2_3_25);
			config.setDefaultEncoding("UTF-8");
			config.setDirectoryForTemplateLoading(new File(templateFilePath));
			config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
			config.setLogTemplateExceptions(false);
			Template template = config.getTemplate(templateFileName);
			template.process(data, writer);
			writer.flush();
			html = writer.toString();
		}catch (Exception ex){
			log.error("获取html内容错误"+ex.getMessage());
			return html;
		}finally{
			try {
				writer.close();
			} catch (IOException e) {
				log.error("关闭流异常"+e.getMessage());
				return html;
			}
		}
		return html;
	}

	private  String getTemplatePath(String templatePath) {
		if(StringUtils.isEmpty(templatePath)){
			return "";
		}
		String path = "";
		int ss = templatePath.lastIndexOf("/");
		if(ss==-1){
			path=templatePath.substring(0,templatePath.lastIndexOf("\\"));
		} else {
			path=templatePath.substring(0,templatePath.lastIndexOf("/"));
		}
		return path;
	}

	private  String getTemplateName(String templatePath) {
		if(StringUtils.isEmpty(templatePath)){
			return "";
		}
		String fileName=templatePath.substring(templatePath.lastIndexOf("/")+1);
		return fileName;
	}

}